const jsonServer = require('json-server');
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
const PORT = process.env.PORT || 3000;
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');

// 动态加载 db 文件夹下的所有 JSON 文件并合并为一个对象
const loadResources = () => {
  const resources = {};
  const dbDir = path.join(__dirname, 'db');
  console.log(`Loading resources from ${dbDir}`);

  const files = fs.readdirSync(dbDir).filter(file => file.endsWith('.json')).map(file => path.basename(file, '.json'));

  files.forEach(file => {
    try {
      const fullPath = path.join(dbDir, `${file}.json`);
      console.log(`Loading ${fullPath}`);
      const data = require(fullPath);
      if (data[file]) {
        resources[file] = data[file];
      } else {
        console.warn(`Warning: ${file}.json does not contain a top-level property named '${file}'.`);
      }
    } catch (err) {
      console.error(`Error loading ${file}.json:`, err.message);
    }
  });

  return resources;
};

let resources = loadResources();
const router = jsonServer.router(resources);

// 中间件来保存更改到文件
const saveToFile = (modifiedResource) => {
  const fullPath = path.join(__dirname, 'db', `${modifiedResource}.json`);
  const data = { [modifiedResource]: resources[modifiedResource] };
  fs.writeFileSync(fullPath, JSON.stringify(data, null, 2), 'utf8');
  console.log(`Saved changes to ${fullPath}`);
};

// 设置文件监视器以支持热更新
const watcher = chokidar.watch('db/*.json', { ignoreInitial: true });
watcher.on('all', (event, path) => {
  console.log(`${event} event occurred on ${path}`);
  resources = loadResources();
  router.db.setState(resources); // 更新数据库状态
  console.log('Database updated.');
});

// 使用默认中间件和路由器
server.use(middlewares);
server.use(jsonServer.bodyParser);

// 在每次路由操作后保存更改
server.use((req, res, next) => {
  const originalSend = res.send;

  res.send = function (body) {
    // 恢复原始 send 方法并执行
    res.send = originalSend;
    const result = res.send(body);

    // 如果是 POST、PUT 或 DELETE 请求，则保存更改
    if (['POST', 'PUT', 'DELETE'].includes(req.method)) {
      // 确定哪个资源被修改了
      const modifiedResource = req.path.split('/')[1]; // 获取 URL 的第一部分作为资源名
      if (resources[modifiedResource]) {
        saveToFile(modifiedResource);
      } else {
        console.warn(`No resource found for path: ${req.path}`);
      }
    }

    return result; // 返回发送结果
  };

  next(); // 确保先处理其他中间件
});

server.use(router);

// 启用 CORS
server.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// 获取当前时间
const startTime = new Date().toISOString();

// 启动服务器并输出访问地址和其他信息
server.listen(PORT, () => {
  console.log(``);
  console.log(`----------------------------------------------------`);
  console.log(`JSON Server started at ${startTime}`);
  console.log(`Listening on http://localhost:${PORT}`);
  console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
  console.log(`----------------------------------------------------`);
  console.log(``);
});